"""
场所班次
场所排班表
"""
from django.db import transaction
from mysqldb.header import *
from .serializers import *
from .FilterBackends import *


class AllinpayPlaceGradeSetViewSet(viewsets.ModelViewSet):
    __title__ = "门店班次"
    __group__ = "门店场所"
    __info__ = {"get": "门店班次列表或详情", "post": "创建班次", "put": "修改班次", "delete": "移除班次"}
    __doc__ = """
    list:\n
    <h4>门店场所班次列表</h4>
    retrieve:\n
    <h4>门店场所班次详情</h4>
        {id} 记录ID
    create:\n
    <h4>门店场所班次创建</h4>
    update:\n
    <h4>门店场所班次修改</h4>
        {id} 记录ID
    delete:\n
    <h4>门店场所班次移除</h4>
        {id} 记录ID
    """
    http_method_names = ["get", "post", "put", "delete"]
    authentication_classes = [MyJWTAuthentication, WeChatJWTAuthentication]
    permission_classes = [MyPermissions | WeChatPermissions]
    serializer_class = AllinpayPlaceGradeSerializer
    queryset = AllinpayPlaceGrade.objects.all()
    filter_backends, filterset_fields = [ListDjangoFilterBackend], ["pid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        def check_sky(s, e):
            """检测是否跨天"""
            return 0 if s < e else 1

        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        x = check_sky(
            serializer.validated_data.get("star"), serializer.validated_data.get("end")
        )
        serializer.save(sky=x)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        def check_sky(s, e):
            """检测是否跨天"""
            return 0 if s < e else 1

        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        x = check_sky(
            serializer.validated_data.get("star"), serializer.validated_data.get("end")
        )
        serializer.save(sky=x)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        # 移除排班表
        pk = instance.id
        AllinpayPlaceGradeList.objects.filter(grade=pk).delete()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayPlaceGradeListSetViewSet(viewsets.ModelViewSet):
    __title__ = "门店排班表"
    __group__ = "门店场所"
    __info__ = {"get": "门店排班表列表或详情", "post": "创建排班表", "delete": "移除排班表"}
    __doc__ = """
    list:\n
    <h4>门店场所排班表列表</h4>
    retrieve:\n
    <h4>门店场所排班表详情</h4>
        {id} 记录ID
    create:\n
    <h4>门店场所排班表创建</h4>
        至少提前一天创建或移除
    delete:\n
    <h4>门店场所排班表移除</h4>
        {id} 记录ID 移除单元格
        至少提前一天创建或移除
    """
    http_method_names = ["get", "post", "delete"]
    authentication_classes = [MyJWTAuthentication, WeChatJWTAuthentication]
    permission_classes = [MyPermissions | WeChatPermissions]
    serializer_class = AllinpayPlaceGradeListSerializer
    queryset = AllinpayPlaceGradeList.objects.all()
    filter_backends = [ListDjangoFilterBackend]
    filterset_class = AllinpayPlaceGradeListV2FilterSet

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        if serializer.validated_data.get("today") <= timezone.now().date():
            raise serializers.ValidationError({"today": "创建失败,请提前至少一天."})
        serializer.save(currentime=timezone.now())
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save(currentime=timezone.now())
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.today <= timezone.now().date():
            raise serializers.ValidationError({"today": "移除失败,请提前至少一天."})
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayAggregationGradeListViewSet(viewsets.ModelViewSet):
    __title__ = "聚合排班表"
    __group__ = "门店场所"
    __info__ = {"post": "聚合排班表"}
    __doc__ = """
    create:\n
    <h4>聚合排班表</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [
        MyJWTAuthentication,
        BoxJWTAuthentication,
        WeChatJWTAuthentication,
    ]
    permission_classes = [MyPermissions | BoxPermissions | WeChatPermissions]
    serializer_class = AllinpayAggregationGradeListSerializer
    queryset = None

    def get_date_range(self, strdate, enddate):
        date_list = []
        while strdate <= enddate:  # 当begin日期小于end日期执行以下
            date_list.append(strdate)  # 返回日期列表
            begin_date_object = datetime.strptime(strdate, "%Y-%m-%d")  # 设定日期格式
            days1_timedelta = timedelta(days=1)
            strdate = (begin_date_object + days1_timedelta).strftime("%Y-%m-%d")
        return date_list

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 创建数据
        db = serializer.data.copy()
        # 序列化日期
        dmap = self.get_date_range(db.get("today")[0], db.get("today")[1])
        for d in dmap:
            if datetime.strptime(d, "%Y-%m-%d").date() <= timezone.now().date():
                raise serializers.ValidationError({"today": "创建失败,请提前至少一天."})
        # 迭代数据
        x = [
            {"pid": u[0], "grade": u[1], "staff": u[2], "today": u[3]}
            for u in product(
                [db.get("pid")], list(db.get("grade")), list(db.get("staff")), dmap
            )
        ]
        # print(x)
        with transaction.atomic():
            """数据库事务"""
            for i in list(x):
                AllinpayPlaceGradeList.objects.update_or_create(
                    defaults={"currentime": timezone.now()}, **i
                )

        return Response({"rescode": 200, "resmsg": "完成"})


# 检查视图
filter_views(globals())
